﻿
var newNode = null;
var oTable = null;
var selected_flowcat_id = '';
var selected_html_node_id = '';
var tree = null;
$(document).ready(function () {

    RefreshTree();

});

function RefreshTree() {
    showLoading();

    var req = {};
    req.opt = "get_nodes";

    $.ajax({
        type: 'POST',
        url: '/Admin/Ajax/SystemCategoryService.aspx',
        data: JSON.stringify(req),
        contentType: 'application/json; charset=utf-8',
        success: function (request, msg) {
            var obj = JSON.parse(request);
            var decoded = $('<div/>').html(obj.Data).text();

            console.log('success: ' + obj.Result);

            CreateTree(decoded);

            setTimeout("hideLoading()", 1000);


        },
        error: function (request, status, error) {
            console.log('error');
            hideLoading();
        }

    });
}

// When selection changed
$('#systemCats').on("changed.jstree", function (e, data) {
    console.log('changed: ' + data.selected);
    var str = data.node.li_attr.class;
    var id = str.replace('id_', "");
    selected_flowcat_id = id;
    selected_html_node_id = data.selected.toString();
    $('a#lnkAddNewRow').show();
    LoadGrid(id);
});

$('a#lnkAddNewRow').click(function (e) {
    // e.preventDefault();
    $('.assign-system').effect("fade", 300);
});

$('#systemCats').on("create_node.jstree", function (data, parent, position) {
    newNode = {};
    newNode.opt = 'create_node';

    var parent_id = GetNodeId($('#' + parent.parent).attr('class'));
    newNode.parent_id = parent_id;
    newNode.text = '';

    console.log('create_node |  ' + parent.parent);
});


// systemCats
$('#systemCats').on("rename_node.jstree", function (node, text, old) {
    if (newNode) {
        newNode.text = text.text;
        newNode.previous_id = text.node.id;

        console.log('newNode detected ' + JSON.stringify(newNode));
        // Call ajax here
        $.ajax({
            type: 'POST',
            url: '/Admin/Ajax/SystemCategoryService.aspx',
            data: JSON.stringify(newNode),
            contentType: 'application/json; charset=utf-8',
            success: function (request, msg) {
                console.log('create_node: success | text: ' + text.text);

                var obj = JSON.parse(request);
                var previous_id = obj.Data.split("|")[0];
                var new_id = obj.Data.split("|")[1];

                // HTML data
                var node_jq = $('#' + previous_id);
                if (node_jq.length > 0)
                    node_jq.addClass('id_' + new_id);

                // Model
                var inst = $.jstree.reference('#systemCats');
                var node = inst._model.data[previous_id]
                if (node)
                    node.li_attr.class = 'id_' + new_id;
            },
            error: function (request, status, error) {
                console.log('error');
            }

        });
        newNode = null;
    }
    else {
        // Rename node case
        var str = text.node.li_attr.class;
        var id = str.replace('id_', "");

        var req = {};
        req.opt = "rename_node";
        req.flowcat_id = id;
        req.flowcat_name = text.text;


        $.ajax({
            type: "POST",
            url: "/Admin/Ajax/SystemCategoryService.aspx",
            data: JSON.stringify(req),
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (request, msg) {
                console.log('rename_node: success | text: ' + text.text);
            }
        });
    }


});

// Delete
$('#systemCats').on("delete_node.jstree", function (obj, text) {
    console.log('delete_node: ' + obj);
    var delete_node = {};
    delete_node.opt = "delete_node";
    delete_node.delete_node_id = GetNodeId($('#' + text.node.id).attr('class'));

    $.ajax({
        type: 'POST',
        url: '/Admin/Ajax/SystemCategoryService.aspx',
        data: JSON.stringify(delete_node),
        contentType: 'application/json; charset=utf-8',
        success: function (request, msg) {

            var obj = JSON.parse(request);


            console.log('delete_node success: ' + obj.Data);
        },
        error: function (request, status, error) {
            console.log('error');
        }

    });
});

// Reorder
$('#systemCats').on("move_node.jstree", function (e, data) {
    var position = data.position;
    var str = data.node.li_attr.class;
    var current_node_id = str.replace('id_', "");

    var req = {};
    req.opt = "reorder_node";
    req.position = position;
    req.current_node = current_node_id;
    req.parent = GetNodeId($("#" + data.parent).attr('class'));
    req.old_parent = GetNodeId($("#" + data.old_parent).attr('class'));
    req.is_new_parent = false;

    if (data.parent == data.old_parent) {
        // Reorder, same parent
        req.is_new_parent = false;
    }
    else {
        // Move node to the new parent
        var new_parent = data.parent;
        req.is_new_parent = true;

    }

    $.ajax({
        type: 'POST',
        url: '/Admin/Ajax/SystemCategoryService.aspx',
        data: JSON.stringify(req),
        contentType: 'application/json; charset=utf-8',
        success: function (request, msg) {
            var obj = JSON.parse(request);

            console.log('reorder_node success: ' + obj.Data);
        },
        error: function (request, status, error) {
            console.log('reorder_node error');
        }

    });
});

function RefreshPage(node_id) {
    window.location = "/Admin/LCASystem/ManageSystemCategories.aspx?selected_html_node_id=" + node_id;
}

function GetNodeId(node) {
    var result = '';
    var strs = node.split(' ');
    for (var i = 0; i < strs.length; i++) {
        var str = strs[i];
        if (str.indexOf('id_') != -1) {
            result = str.replace('id_', "");
            break;
        }
    }

    return result;
}

function LoadGrid(systemcat_id) {
    var req = {};
    req.opt = "get_systems_by_systemcategory";
    req.systemcat_id = systemcat_id;

    $.ajax({
        type: "POST",
        url: "/Admin/Ajax/SystemCategoryService.aspx",
        data: JSON.stringify(req),
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: buildGrid
    });


}

function buildGrid(request, msg) {
    console.log('get_systems_by_systemcategory: success');

    var gridData = JSON.parse(request.Data);

    oTable = null;
    oTable = $('#example').dataTable({
        "bProcessing": true,
        "bDestroy": true,
        "bPaginate": false,
        "bAutoWidth": false,
        "bFilter": false,
        "aaData": gridData,
        "aoColumns": [
        //                    { "mDataProp": "fID", "sTitle": "ID", "sClass": "cID", "bSearchable": false, "bVisible": true },
                    {"mDataProp": "RowCount", "bSortable": false, "sTitle": "#", "sClass": "cRowCount", "bVisible": true, "sDefaultContent": "" },
                    { "mDataProp": "Name", "bSortable": false, "sTitle": "Name", "sClass": "cName", "bSearchable": true, "bVisible": true },
                    { "mDataProp": "fUnit", "bSortable": false, "sTitle": "Unit", "sClass": "cUnit", "bSearchable": true, "bVisible": true },
                    { "mDataProp": null, "bSortable": false, "sTitle": "Delete", "sClass": "cDelete", "sDefaultContent": "<input id='btnDelete' class='button' type='button' value='Delete' />", "bVisible": true }
                ],
        "fnCreatedRow": function (nRow, aData, iDataIndex) {
            // Assign id to 'tr'
            $(nRow).attr('id', aData.fID);
            $('input#btnDelete', nRow).click(function (e) {
                if (confirm('Are you sure do you want to delete this ?')) {

                    var req = {};
                    req.opt = "delete_system_systemcategory";
                    req.fcf_id = aData.fID;

                    ///////
                    $.ajax({
                        type: "POST",
                        url: "/Admin/Ajax/SystemCategoryService.aspx",
                        data: JSON.stringify(req),
                        contentType: "application/json; charset=utf-8",
                        dataType: "json",
                        success: function (request, msg) {
                            console.log('delete_system_systemcategory: success');
                            RefreshPage(selected_html_node_id);
                        }
                    });

                }
            });
        }
    }).rowReordering({


        fnAfterNodeDrop: function (table) {
            UpdateSystemsGrid();
        }

    });

}

function UpdateSystemsGrid() {
    var req = {};
    req.opt = "update_systems_systemcategory_order";
    req.lists = [];
    //var index = 0;

    $("table#example > tbody > tr").each(function () {
        var fid = $(this).attr('id');
        req.lists.push({ id: fid });

    });

    ///////
    $.ajax({
        type: "POST",
        url: "/Admin/Ajax/SystemCategoryService.aspx",
        data: JSON.stringify(req),
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function (request, msg) {
            console.log('update_systems_systemcategory_order: success');
        }
    });

}

function CreateTree(decoded) {
    $('#systemCats').html(decoded);
    tree = $('#systemCats').jstree({
        "plugins": ["dnd", "contextmenu"],
        "contextmenu": {
            "items": function ($node) {
                var contextItems = {
                    "Create": {
                        "label": "Create a category",
                        "icon": "/Admin/Images/create.png",
                        "action": function (data) {
                            console.log('contextmenu.create');
                            var inst = $.jstree.reference(data.reference),
							        obj = inst.get_node(data.reference);
                            inst.create_node(obj, {}, "last", function (new_node) {
                                setTimeout(function () { inst.edit(new_node); }, 0);
                            });
                        }
                    },
                    "Rename": {
                        "label": "Rename",
                        "icon": "/Admin/Images/rename.png",
                        "action": function (data) {
                            console.log('contextmenu.rename');
                            var inst = $.jstree.reference(data.reference),
							        obj = inst.get_node(data.reference);
                            inst.edit(obj);
                        }
                    },
                    "Delete": {
                        "label": "Delete",
                        "icon": "/Admin/Images/delete.png",
                        "action": function (data) {
                            if (confirm("Are you sure to delete this?")) {
                                var inst = $.jstree.reference(data.reference),
							            obj = inst.get_node(data.reference);
                                if (inst.is_selected(obj)) {
                                    inst.delete_node(inst.get_selected());
                                }
                                else {
                                    inst.delete_node(obj);
                                }
                            }
                        }
                    },
                    "ccp": false
                };

                if (isRootNode($node)) {
                    delete contextItems.Delete;
                    delete contextItems.Rename;
                }

                return contextItems;
            }
        },
        "core": {
            "check_callback": true
        }


    });

    // Select node in tree from url query string
    var html_node_id = $.getUrlVar('selected_html_node_id');
    if (html_node_id)
        $('#systemCats').jstree('select_node', html_node_id);

    console.log('html_node_id: ' + html_node_id);


}

function isRootNode(node) {
    return node.li_attr.class == 'id_3d28cef3-e1bb-4e5b-9325-3f876a94c517';
}

function showLoading() {
    $(".loading").show();
}

function hideLoading() {
    $(".loading").hide();
}